package com.fs.m.server;

import com.fs.m.server.domain.Client;
import com.fs.m.server.domain.RequestContext;
import com.fs.m.server.domain.Result;
import com.fs.m.server.domain.ResultCode;
import com.fs.m.server.function.Function;
import com.fs.m.server.function.FunctionManager;
import com.fs.m.server.util.GsonUtil;
import com.fs.m.server.util.MapUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 入口servlet
 *
 * User: zhuguoyin
 * Date: 13-10-5
 * Time: 下午2:35
 * To change this template use File | Settings | File Templates.
 */
public class EntryServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String body = request.getParameter("body");
        Map<String, Object> bodyMap;
        try {
            bodyMap = GsonUtil.fromJson(body, HashMap.class);
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(ResultCode.PARAMETER_ERROR.getCode());
            String s = new Gson().toJson(result);
            response.getWriter().write(s);
            return;
        }
        RequestContext requestContext = new RequestContext();
        if (bodyMap != null) {
            requestContext.setParam(MapUtil.getMap(bodyMap, "param"));
            Map clientMap = MapUtil.getMap(bodyMap, "client");
            Client client = new Client();
            client.fromMap(clientMap);
            requestContext.setClient(client);
        }
        requestContext.setRequestMap(request.getParameterMap());
        RequestContext.set(requestContext);

        Function function = FunctionManager.getFunction(request.getParameter("f"));
        if (function == null) {
            Result result = new Result();
            result.setCode(ResultCode.NO_FUNCTION.getCode());
            String s = GsonUtil.toJSon(result);
            response.getWriter().write(s);
            return;
        }

        try {
            Result result = function.execute();
            String s = GsonUtil.toJSon(result);
            response.getWriter().write(s);
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(ResultCode.EXCEPTION.getCode());
            String s = GsonUtil.toJSon(result);
            response.getWriter().write(s);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }

}
